package com.alesj.newsfeed.web.view;

import com.alesj.newsfeed.data.Tokenizable;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.io.PrintWriter;

/**
 * @author <a href="mailto:ales.justin@gmail.com">Ales Justin</a>
 */
public class CSVView extends AbstractView {

    /** The content type for an CSV response */
    private static final String CONTENT_TYPE = "text/csv";

    private String elementsKey = "elements";

    public CSVView() {
        setContentType(CONTENT_TYPE);
    }

    protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Collection<Tokenizable> elements = (Collection<Tokenizable>) model.get(elementsKey);
        if (elements != null) {
            response.setContentType(getContentType());
            PrintWriter writer = response.getWriter();
            for (Tokenizable element : elements) {
                List tokens = element.getTokens();
                boolean comma = false;
                for (Object token : tokens) {
                    if (comma) writer.write(',');
                    writer.write(token != null ? token.toString() : "");
                    comma = true;
                }
                writer.write('\n');
            }
            writer.write('\n');
            writer.flush();
        } else {
            logger.warn("No " + elementsKey + " found in model map: " + model);
        }
    }

    public void setElementsKey(String elementsKey) {
        this.elementsKey = elementsKey;
    }

}
